from django.shortcuts import render, get_object_or_404, redirect
import requests
import json
from django.http import JsonResponse, HttpResponse, Http404
import os
from django.conf import settings
import mimetypes
from django.utils import timezone
from django.urls import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Article, Tag

# 安全的根目录文件访问视图
def root_file_view(request, path=''):
    """处理根目录文件访问的视图函数"""
    # 定义允许访问的文件扩展名
    allowed_extensions = ['.html', '.css', '.js', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.txt', '.pdf']
    
    # 获取文件路径
    file_path = os.path.join(settings.BASE_DIR, path)
    
    # 安全检查：确保文件在项目根目录内
    if not os.path.abspath(file_path).startswith(os.path.abspath(settings.BASE_DIR)):
        raise Http404("文件不存在或访问被拒绝")
    
    # 检查文件是否存在
    if not os.path.isfile(file_path):
        # 如果是访问首页，返回IP分析页面
        if path == '' or path == 'index.html' or path == 'index.htm':
            return ip_analysis_view(request)
        raise Http404("文件不存在")
    
    # 检查文件扩展名是否允许
    _, ext = os.path.splitext(file_path)
    if ext.lower() not in allowed_extensions:
        raise Http404("不支持的文件类型")
    
    # 确定MIME类型
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type:
        mime_type = 'application/octet-stream'
    
    # 读取文件内容并返回
    try:
        with open(file_path, 'rb') as f:
            content = f.read()
        return HttpResponse(content, content_type=mime_type)
    except Exception as e:
        raise Http404(f"无法读取文件: {str(e)}")

def ip_analysis_view(request):
    """IP地址分析视图函数，处理GET和POST请求"""
    if request.method == 'POST':
        # 获取用户输入的IP地址
        ip_address = request.POST.get('ip_address', '')
        
        if ip_address:
            try:
                # 调用ip-api.com API获取IP地址信息
                response = requests.get(f'http://ip-api.com/json/{ip_address}?lang=zh-CN', timeout=5)
                if response.status_code == 200:
                    ip_data = response.json()
                    # 检查查询是否成功
                    if ip_data.get('status') == 'success':
                        return render(request, 'ip_analysis/result.html', {'ip_data': ip_data})
                    else:
                        error_message = f"查询失败: {ip_data.get('message', '未知错误')}"
                        return render(request, 'ip_analysis/index.html', {'error': error_message})
                else:
                    return render(request, 'ip_analysis/index.html', {'error': f'API请求失败，状态码: {response.status_code}'})
            except Exception as e:
                return render(request, 'ip_analysis/index.html', {'error': f'请求过程中发生错误: {str(e)}'})
        else:
            return render(request, 'ip_analysis/index.html', {'error': '请输入有效的IP地址'})
    
    # 获取客户端真实IP地址（支持代理环境）
    client_ip = request.META.get('HTTP_X_REAL_IP')
    if not client_ip:
        # 从代理头获取IP（处理多个代理情况）
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '')
        if x_forwarded_for:
            client_ip = x_forwarded_for.split(',')[0].strip()
    if not client_ip:
        client_ip = request.META.get('REMOTE_ADDR')
    
    # 获取IP地理位置信息
    geo_location = None
    if client_ip:
        try:
            # 调用ip-api.com API获取地理位置信息
            response = requests.get(f'http://ip-api.com/json/{client_ip}?lang=zh-CN', timeout=5)
            if response.status_code == 200:
                geo_data = response.json()
                if geo_data.get('status') == 'success':
                    geo_location = {
                        'country': geo_data.get('country'),
                        'province': geo_data.get('regionName'),
                        'city': geo_data.get('city')
                    }
        except Exception as e:
            pass  # 忽略API调用错误
    
    # 获取热门文章（按访问量排序，最多5条）
    hot_articles = Article.objects.filter(
        status="published", 
        publish_date__lte=timezone.now()
    ).order_by("-view_count", "-publish_date")[:5]
    
    # 获取最新文章（最新添加的文章，最多5条）
    latest_articles = Article.objects.filter(
        status="published", 
        publish_date__lte=timezone.now()
    ).order_by("-publish_date")[:5]
    
    # 获取热门网络工具（标签为"热门网络工具"的内容，按访问量排序，最多5条）
    hot_tools_tag = Tag.objects.filter(name="热门网络工具").first()
    hot_tools = []
    if hot_tools_tag:
        hot_tools = Article.objects.filter(
            status="published", 
            publish_date__lte=timezone.now(),
            tags=hot_tools_tag
        ).order_by("-view_count", "-publish_date")[:5]
    
    # GET请求时显示表单、客户端IP和地理位置信息
    # 检查是否是通过curl命令请求
    user_agent = request.META.get('HTTP_USER_AGENT', '')
    if 'curl' in user_agent:
        return JsonResponse({'client_ip': client_ip})
    return render(request, 'ip_analysis/index.html', {
        'client_ip': client_ip,
        'geo_location': geo_location,
        'hot_articles': hot_articles,
        'latest_articles': latest_articles,
        'hot_tools': hot_tools
    })

def api_ip_analysis(request):
    """API接口，用于通过AJAX请求获取IP地址分析结果"""
    if request.method == 'GET':
        ip_address = request.GET.get('ip_address', '')
        
        if ip_address:
            try:
                response = requests.get(f'http://ip-api.com/json/{ip_address}?lang=zh-CN', timeout=5)
                if response.status_code == 200:
                    return JsonResponse(response.json())
                else:
                    return JsonResponse({'status': 'error', 'message': f'API请求失败，状态码: {response.status_code}'}, status=400)
            except Exception as e:
                return JsonResponse({'status': 'error', 'message': f'请求过程中发生错误: {str(e)}'}, status=500)
        else:
            return JsonResponse({'status': 'error', 'message': '请提供有效的IP地址'}, status=400)
    
    return JsonResponse({'status': 'error', 'message': '只支持GET请求'}, status=405)


def article_list(request):
    """文章列表视图，支持标签筛选和分页"""
    tag_name = request.GET.get('tag')
    articles = Article.objects.filter(
        status="published",
        publish_date__lte=timezone.now()
    ).order_by("-is_sticky", "-publish_date")
    
    if tag_name:
        articles = articles.filter(tags__name=tag_name)
    
    # 分页处理
    paginator = Paginator(articles, 10)  # 每页显示10篇文章
    page = request.GET.get('page')
    try:
        paginated_articles = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，显示第一页
        paginated_articles = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，显示最后一页
        paginated_articles = paginator.page(paginator.num_pages)
    
    # 获取热门网络工具（标签为"热门网络工具"的内容）
    hot_tools_tag = Tag.objects.filter(name="热门网络工具").first()
    hot_tools = []
    if hot_tools_tag:
        hot_tools = Article.objects.filter(
            status="published",
            publish_date__lte=timezone.now(),
            tags=hot_tools_tag
        ).order_by("-publish_date")
    
    # 获取所有文章标签
    article_tags = Tag.objects.filter(
        is_active=True,
        articles__status="published",
        articles__publish_date__lte=timezone.now()
    ).distinct().order_by("name")
    
    # 获取热门标签（使用次数大于0的标签，按使用次数排序）
    popular_tags = Tag.objects.filter(
        is_active=True,
        usage_count__gt=0
    ).order_by("-usage_count")[:20]
    
    return render(request, 'ip_analysis/article_list.html', {
        'articles': paginated_articles,
        'hot_tools': hot_tools,
        'current_tag': tag_name,
        'article_tags': article_tags,
        'popular_tags': popular_tags
    })


def article_detail(request, article_id):
    """文章详情页视图，包含SEO优化"""
    # 获取文章对象，不存在则返回404
    article = get_object_or_404(Article, id=article_id, status="published", publish_date__lte=timezone.now())
    
    # 增加阅读量
    article.view_count += 1
    article.save()
    
    # 获取相关文章（基于相同标签）
    related_articles = Article.objects.filter(
        tags__in=article.tags.all(),
        status="published",
        publish_date__lte=timezone.now()
    ).exclude(id=article.id).distinct().order_by("-publish_date")[:3]
    
    # 获取热门网络工具
    hot_tools_tag = Tag.objects.filter(name="热门网络工具").first()
    hot_tools = []
    if hot_tools_tag:
        hot_tools = Article.objects.filter(
            status="published",
            publish_date__lte=timezone.now(),
            tags=hot_tools_tag
        ).order_by("-publish_date")
    
    context = {
        'article': article,
        'related_articles': related_articles,
        'hot_tools': hot_tools
    }
    
    return render(request, 'ip_analysis/article_detail.html', context)
